package com.hp.fremarker.web.handler;

import com.hp.fremarker.web.mvc.Controller;
import com.hp.fremarker.web.mvc.RequestMapping;
import com.hp.fremarker.web.mvc.RequestParam;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author dongxing
 **/
public class HandlerManager {

    public static List<MappingHandler> mappingHandlerList = new ArrayList<>();

    public static void resolveMappingHandler(List<Class<?>> classList) {

        for (Class<?> aClass : classList) {
            // 判断是否包含controller注解
            if (aClass.isAnnotationPresent(Controller.class)) {
                parseHandlerFromController(aClass);
            }
        }
    }

    private static void parseHandlerFromController(Class<?> aClass) {

        // 获取类中的所有的方法
        Method[] declaredMethods = aClass.getDeclaredMethods();

        // 遍历方法
        for (Method declaredMethod : declaredMethods) {

            // 判断方法上是否有RequestMapping注解
            if (!declaredMethod.isAnnotationPresent(RequestMapping.class)) {
                continue;

            }
            // 获取RequestMapping注解中的值
            String uri = declaredMethod.getDeclaredAnnotation(RequestMapping.class).value();
            List<String> paramList = new ArrayList<>();
            for (Parameter parameter : declaredMethod.getParameters()) {

                // 方法的参数的RequestParam的值
                if (parameter.isAnnotationPresent(RequestParam.class)) {
                   paramList.add(parameter.getAnnotation(RequestParam.class).value());
                }

            }
            String[] params = paramList.toArray(new String[paramList.size()]);
            MappingHandler mappingHandler = new MappingHandler(uri,declaredMethod,aClass,params);
            HandlerManager.mappingHandlerList.add(mappingHandler);
        }
    }
}
